<script lang="ts" setup name="order">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { request } from "@/service/request";
import API from "@/service/api/order";
import { mStyles } from "@/utils/useStyles";
import ServiceOrderItem from './plugin/index.vue'
import { useRoute } from 'vue-router';
import { useStore } from '@/stores/user';
import { someFieldStore } from "@/stores/somefield";
import { getUrlParamValue } from "@/utils/getUrlParams";
import { useDynamicKeepAlive } from '@/utils/keepAliveUtils'
import { useFullPage } from "@/hook/useFullPage";

// 新增：定义状态计数类型并添加索引签名
interface StatusCounts {
    total: number;
    waitAppraise: number;
    processing: number;
    finish: number;
    [key: string]: number; // 添加字符串索引签名
}

const mParameter = reactive({
    page: 1,
    page_size: 10,
    handle_status: '', //状态筛选参数
    order_num: '', //工单号
    game_id: 0,
});

interface TabConfig {
    name: keyof StatusCounts;
    title: string;
}

const mActive = ref('');
const mRoute = useRoute();

const mOrderList = ref<any>([]);

// 各状态数量统计
const mStatusCounts = ref<StatusCounts>({
    total: 0,
    processing: 0,
    waitAppraise: 0,
    finish: 0
});


//滚动翻页
const mLoading = ref(false);
const mFinished = ref(false);
const clkOnLoad = () => {
    let total_page = computed(() => Math.ceil(mStatusCounts.value[mActive.value] / mParameter.page_size));

    // 判断是否是最后一页
    if (mParameter.page >= total_page.value) {
        if (total_page.value === 0) {
            mLoading.value = false;
            mFinished.value = false;
            return;
        }
        mFinished.value = true;
        return;
    }

    //判断是否加载完毕
    if (mOrderList.value.length == mStatusCounts.value[mActive.value]) {
        mFinished.value = true;
        return;
    }

    mParameter.page++;
    clkGetOrderlist();
};


//未登录查询工单
const mSomefield = someFieldStore();
const mUser = useStore();
const mApiurl = ref();
if (mSomefield.order_num != "") {
    mApiurl.value = API.orderWrecordList;
    mParameter.order_num = mSomefield.order_num; // 使用工单号查询
} else {
    mApiurl.value = API.orderRecordList;
}

const urlGameId = getUrlParamValue("game_id", mSomefield.clientfields);
mParameter.game_id = urlGameId !== null && !isNaN(Number(urlGameId)) ? Number(urlGameId) : 0;  //如果有给game_id参数就用game_id，没有就用0


if (getUrlParamValue('access_token', mSomefield.clientfields) == null) {
    mParameter.game_id = 0;  //客户端登录，game_id为0
}

//阻止切换
const clkBeforeChange = (name: string) => {
    return true; // 允许切换到其他标签页
};

//切换标签页时重置状态
const clkChangeOrderList = (name: { name: string }) => {
    if(!mUser.state && mSomefield.order_num == "") return;  //没有登录并且本地没有工单号切换列表不请求
    mFinished.value = false;
    mLoading.value = false;
    mActive.value = name.name;
    mParameter.handle_status = mActive.value;
    mParameter.page = 1;
    mOrderList.value = [];
    clkGetOrderlist()
};

// 更新数量统计
const clkGetOrderlist = async (e?: string) => {
    //total就是全部
    if (mActive.value === 'total') {
        mParameter.handle_status = '';
    } else {
        mParameter.handle_status = mActive.value;
    }
    const { data } = await request.post<any>(mApiurl.value, mParameter);
    if (data.data) {
        mOrderList.value.push(...data.data);
        mLoading.value = false;
    }
};

if (mRoute.query.active) {
    mParameter.page = 1;
    mActive.value = mRoute.query.active as string;
}



// 初始化时获取所有状态数量
const { addCachedView } = useDynamicKeepAlive()
const clkInitStatusCounts = async () => {
    // 状态映射关系：API参数 -> mStatusCounts属性
    const statusMap: Record<string, keyof StatusCounts> = {
        '': 'total',
        'processing': 'processing',
        'waitAppraise': 'waitAppraise',
        'finish': 'finish'
    };

    const statusTypes = Object.keys(statusMap);
    for (const status of statusTypes) {
        mParameter.handle_status = status;
        const { data } = await request.post<any>(mApiurl.value, mParameter);
        const countKey = statusMap[status];
        mStatusCounts.value[countKey] = data.page_info?.total_number || 0;
        if (mActive.value === countKey) {
            mOrderList.value = data.data;
        }
    }

    //初始化成功添加到缓存列表
    addCachedView(mRoute)
};

//有登录态或者本地有工单号才请求工单列表
if(mUser.state || mSomefield.order_num != ""){
    clkInitStatusCounts()
}



//重置对应列表数据
const clkBeforeClose = () => {
    clkInitStatusCounts();
};

//配置标签页
const mTabConfigs = computed<TabConfig[]>(() => [
    { name: 'total', title: `全部(${mStatusCounts.value.total})` },
    { name: 'processing', title: `处理中(${mStatusCounts.value.processing})` },
    { name: 'waitAppraise', title: `待评价(${mStatusCounts.value.waitAppraise})` },
    { name: 'finish', title: `处理完成(${mStatusCounts.value.finish})` }
]);


//动态获取导航栏占位符的高度
const placeholderHeight = ref('46px');

// 在组件挂载后动态获取并设置高度
onMounted(() => {
    nextTick(() => {
        const navBar = document.querySelector('.van-nav-bar');
        if (navBar) {
            const actualHeight = (navBar as HTMLElement).offsetHeight-2 + 'px';
            placeholderHeight.value = actualHeight;
        }
    });
});

const { pageRef } = useFullPage()
</script>

<template>
    <cNavbar iTitle="服务记录" :iFontColor="mStyles?.color2" :iBgColor="mStyles?.color10" leftArrow iFixed></cNavbar>
    <div  ref="pageRef" class="bg-[#F6F6F6]">
        <van-tabs v-model:active="mActive" :color="mStyles?.color1" @click-tab="clkChangeOrderList" :ellipsis="false"
            :before-change="clkBeforeChange" :offset-top="placeholderHeight" sticky>
            <van-tab v-for="(item, index) in mTabConfigs" :key="index" :title="item.title" :name="item.name">
                <van-list v-model:loading="mLoading" :finished="mFinished" finished-text="没有更多了" @load="clkOnLoad"
                    class="gr-list" :immediate-check="false">
                    <ServiceOrderItem v-for="(items, index) in mOrderList" :key="items['id']" :item="items"
                        @is-Urgent="clkBeforeClose" @is-Appraise="clkBeforeClose" />
                    <van-empty image="/nothing.png" image-size="42.667vmin" description="暂无数据"
                        v-show="mOrderList == null || mOrderList.length == 0" />
                </van-list>
            </van-tab>
        </van-tabs>
    </div>
</template>

<style lang="scss" scoped>
:deep(.van-tabs__nav--complete) {
    padding-left: 0;
    padding-right: 0;
}

:deep(.van-tab__text) {
    font-size: 30px;
}

:deep(.van-tabs__line) {
    background: #F90919;
    width: 48px;
    bottom: 35px;
}

.gr-list {
    padding: 24px;
    background: #F6F6F6;
}
</style>